package bblrtc

import (
	"sync/atomic"
	"time"
)

type Peer struct {
	Member         string        `json:"member"`
	Sid            string        `json:"sid"`
	NodeId         string        `json:"nodeId"`
	LastActiveTime time.Time     `json:"lastActiveTime"`
	LoginTime      time.Time     `json:"loginTime"`
	DeviceId       string        `json:"deviceId"`
	router         *Router       `json:"-"`
	channel        chan *Message `json:"-"`
	last_msg       *Message      `json:"-"`
	kickNotify     chan bool
	status         int32
	counter        int32
	rtcsession     *RTCSession
}

func new_peer(user *User, devId, nodeId string, router *Router) *Peer {
	now := time.Now()
	return &Peer{Member: user.Name,
		Sid:            UUID(),
		LoginTime:      now,
		LastActiveTime: now,
		DeviceId:       devId,
		NodeId:         nodeId,
		router:         router,
		channel:        make(chan *Message, 10),
		kickNotify:     make(chan bool),
	}
}

func (s *Peer) Message() chan *Message {
	return s.channel
}

func (s *Peer) Coming() {
	s.LastActiveTime = time.Now()
	if atomic.LoadInt32(&s.counter) > 0 {
		s.kickNotify <- true
	}
	atomic.AddInt32(&s.counter, 1)
}

func (s *Peer) Gone() {
	atomic.AddInt32(&s.counter, -1)
}

func (s *Peer) ActiveCount() int32 {
	return atomic.LoadInt32(&s.counter)
}

func (s *Peer) Calling() {
	atomic.StoreInt32(&s.status, 1)
}

func (s *Peer) UnCalling() {
	atomic.StoreInt32(&s.status, 2)
}

func (s *Peer) IsCalling() bool {
	return atomic.LoadInt32(&s.status) == 1
}

func (s *Peer) KickedNotify() chan bool {
	return s.kickNotify
}

func (s *Peer) IsOnline() bool {
	return atomic.LoadInt32(&s.status) != 3 && time.Now().Sub(s.LastActiveTime) < time.Duration(30*time.Second)
}

func (s *Peer) Send(msg *Message) bool {
	if s.IsOnline() {
		s.channel <- msg
		return true
	}
	return false
}

func (s *Peer) Close() {
	atomic.StoreInt32(&s.status, 3)
	if s.rtcsession != nil {
		s.rtcsession.close()
		s.rtcsession = nil
	}
	s.router.RemovePeer(s.Sid)
	close(s.channel)
}
